﻿using System;
using System.Collections.Generic;
using System.Web.Routing;
using System.Text;
using System.Web.Mvc;

namespace ScoutNET.Helpers
{
    public static class RadioButtonListHelper
    {
        public static MvcHtmlString RadioButtonList(this HtmlHelper htmlHelper, string name, List<RadioButtonListInfo> listInfo)
        {
            return RadioButtonList(htmlHelper, name, listInfo, ((IDictionary<string, object>)null));
        }

        public static MvcHtmlString RadioButtonList(this HtmlHelper htmlHelper, string name, List<RadioButtonListInfo> listInfo, object htmlAttributes)
        {
            return RadioButtonList(htmlHelper, name, listInfo, ((IDictionary<string, object>)new RouteValueDictionary(htmlAttributes)));
        }

        public static MvcHtmlString RadioButtonList(this HtmlHelper htmlHelper, string name, List<RadioButtonListInfo> listInfo, IDictionary<string, object> htmlAttributes)
        {
            if (String.IsNullOrEmpty(name))
                throw new ArgumentException("The argument must have a value", "name");
            if (listInfo == null)
                throw new ArgumentNullException("listInfo");
            if (listInfo.Count < 1)
                throw new ArgumentException("The list must contain at least one value", "listInfo");

            StringBuilder sb = new StringBuilder();

            foreach (RadioButtonListInfo info in listInfo)
            {
                TagBuilder builder = new TagBuilder("input");
                if (info.IsChecked) builder.MergeAttribute("checked", "checked");

                builder.MergeAttributes<string, object>(htmlAttributes);
                builder.MergeAttribute("type", "radio");
                builder.MergeAttribute("value", info.Value);
                builder.MergeAttribute("name", name);
                builder.InnerHtml = info.DisplayText;

                sb.Append(builder.ToString(TagRenderMode.Normal));
            }

            return MvcHtmlString.Create(sb.ToString());
       }
    }
    
    // This the information that is needed by each checkbox in the
    // CheckBoxList helper.
    public class RadioButtonListInfo {

        public RadioButtonListInfo(string value, string displayText, bool isChecked)
        {
            this.Value = value;
            this.DisplayText = displayText;
            this.IsChecked = isChecked;
        }

        public string Value { get; private set; }
        public string DisplayText { get; private set; }
        public bool IsChecked { get; private set; }
    }
}
